import { Button, StyleSheet, Text, View, Modal } from 'react-native';
import React, { useRef, useState } from 'react';
import {
  Camera,
  useCameraDevice,
  useCameraFormat,
  useCameraPermission,
} from 'react-native-vision-camera';
import { TestSuite, TestCase, Tester } from '@rnoh/testerino';
import { CameraRoll } from '@react-native-camera-roll/camera-roll';

export function FpsTest() {
  const device = useCameraDevice('back');
  const { hasPermission, requestPermission } = useCameraPermission();
  const camera = useRef<Camera>(null);

  if (!device) {
    return <Text>No Devices</Text>;
  }

  if (!hasPermission) {
    requestPermission();
  }

  const [audio, setAudio] = useState(false);
  const [flash, setFlash] = useState<'off' | 'on'>('off');
  const [preview, setPreview] = useState(true);
  const [videoCodec, setVideoCodec] = useState<'h265' | 'h264'>('h265');
  const [videoStabilizationMode, setVideoStabilizationMode] = useState<
    'off' | 'standard' | 'cinematic' | 'cinematic-extended' | 'auto'
  >('auto');
  const [videoHdr, setVideoHdr] = useState(false);
  // 添加加载弹窗状态
  const [isLoading, setIsLoading] = useState(false);

  const [startStatus, seteStartStatus] = useState('end');
  const [videoFile, setVideoFile] = useState<string>('');
  const [videoPath, setVideoPath] = useState<string>('');
  const [fps, setFps] = useState<number>(30);

  const format = useCameraFormat(device, [
    { videoResolution: { width: 1920, height: 1080 } },
    { fps: fps },
  ]);

  const onStart = async () => {
    setVideoPath('');
    setVideoFile('');
    seteStartStatus('start');
    await camera.current?.startRecording({
      fileType: 'mp4',
      flash: flash,
      onRecordingError: error => {
        seteStartStatus('end');
        setIsLoading(false); // 错误时关闭加载
        console.log(
          `videoStartParmas CameraSession: onRecordingError.${JSON.stringify(
            error,
          )}`,
        );
      },
      onRecordingFinished: video => {
        seteStartStatus('end');
        setIsLoading(false); // 完成时关闭加载
        video && setVideoFile(JSON.stringify(video));
        video?.path && setVideoPath(video.path);
      },
      videoBitRate: 'extra-low',
      videoCodec: videoCodec,
    });
  };

  const onPause = async () => {
    seteStartStatus('pause');
    camera.current?.pauseRecording();
  };

  const onStop = async () => {
    seteStartStatus('end');
    setIsLoading(true); // 开始停止时显示加载
    camera.current?.stopRecording();
  };

  const onResume = async () => {
    seteStartStatus('start');
    camera.current?.resumeRecording();
  };

  return (
    <Tester>
      <TestSuite name="fps">
        <TestCase itShould={`fps:${fps}`}>
          <View>
            <Text>注意：先设置fps，后点击开始按钮</Text>
          </View>
          <View>
            <Text>录像结果:{videoFile}</Text>
          </View>
          {videoPath && (
            <View style={{ height: 50 }}>
              <Button
                title="SaveAsset"
                onPress={() => {
                  CameraRoll.saveAsset(videoPath).then(res => {
                    setTimeout(() => {
                      setVideoPath('');
                      setVideoFile('');
                    }, 500);
                  });
                }}
              />
            </View>
          )}
          <Camera
            style={style.cameraPreview}
            ref={camera}
            isActive={true}
            preview={preview}
            device={device}
            video={true}
            audio={audio}
            videoHdr={videoHdr}
            videoStabilizationMode={videoStabilizationMode}
            fps={fps}
            format={format}
          />
          <View style={style.actionBtn}>
            <>
              {videoHdr && videoCodec === 'h264' ? (
                <Text>videoHdr为true时，videoCodeC只能设置为h265; </Text>
              ) : (
                <>
                  {startStatus === 'end' ? (
                    <Button title="开始" onPress={onStart}></Button>
                  ) : (
                    ''
                  )}
                  {startStatus === 'start' ? (
                    <Button title="暂停" onPress={onPause}></Button>
                  ) : (
                    ''
                  )}
                  {startStatus === 'pause' ? (
                    <Button title="恢复" onPress={onResume}></Button>
                  ) : (
                    ''
                  )}
                  {startStatus !== 'end' ? (
                    <Button title="停止" onPress={onStop}></Button>
                  ) : (
                    ''
                  )}
                </>
              )}
            </>
            <Button
              title={'set:20'}
              onPress={() => {
                setFps(20);
              }}></Button>
            <Button
              title={`set:30`}
              onPress={() => {
                setFps(30);
              }}></Button>
          </View>

          {/* 加载弹窗 */}
          <Modal
            visible={isLoading}
            transparent={true}
            animationType="fade"
            onRequestClose={() => setIsLoading(false)}
          >
            <View style={style.loadingContainer}>
              <View style={style.loadingBox}>
                <Text style={style.loadingText}>请稍候，处理中...</Text>
              </View>
            </View>
          </Modal>
        </TestCase>
      </TestSuite>
    </Tester>
  );
}

const style = StyleSheet.create({
  cameraPreview: { width: '100%', aspectRatio: 56 / 100 },
  actionBtn: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    padding: 10,
    gap: 5,
  },
  text: {
    fontSize: 20,
    textAlign: 'center',
    color: '#000',
  },
  // 加载弹窗样式
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  loadingBox: {
    backgroundColor: 'white',
    padding: 20,
    borderRadius: 10,
    alignItems: 'center',
  },
  loadingText: {
    marginTop: 10,
    fontSize: 16,
  },
});
